package account

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/common/enum"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type BindCreateAccountApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewBindCreateAccountApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *BindCreateAccountApiLogic {
	hostname, _ := os.Hostname()
	return &BindCreateAccountApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *BindCreateAccountApiLogic) BindCreateAccountApi(req *types.BindCreateAccountReq) (resp string, err error) {
	// 1.只有企业号才可以操作
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	if accountInfo.AccountType != enum.EnterpriseEnum {
		return "", errors.New("只有企业账号才可以创建账号")
	}
	_, err = dao.AccountEntity.WithContext(l.ctx).Where(dao.AccountEntity.Username.Eq(req.Username)).First()
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		l.Logger.Error(req.Username + "存在,不能重复")
		return "", errors.New("账号存在,不能重复")
	}
	roleEntity, err := service.RoleService.GetByCodeApi(l.ctx, accountInfo.EnterpriseId, enum.RoleCode01Enum)
	if err != nil {
		return "", errors.New("当前企业没有设置店长角色")
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	enterprisePersonEntity := model.EnterprisePersonEntity{
		EnterpriseID: accountInfo.EnterpriseId, // 关联到enterprise表主键id
		Name:         req.Name,                 // 员工姓名
		Mobile:       req.Mobile,               // 员工手机号码
		RoleID:       roleEntity.ID,            // 角色id,关联到role表主键id
	}
	if err = service.EnterprisePersonService.CreateApi(l.ctx, tx, &enterprisePersonEntity); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", err
	}
	// 密码加密处理
	salt := utils.GeneratorString(utils.GeneratorRandom(5, 10))
	newPassword := utils.Md5(req.Password, salt)
	if err = tx.AccountEntity.WithContext(l.ctx).
		Omit(dao.AccountEntity.LastLoginIP, dao.AccountEntity.LastLoginDate).
		Create(&model.AccountEntity{
			Username:     req.Username,
			Password:     newPassword,
			Salt:         salt,
			Avatar:       req.Avatar, // 头像
			AccountType:  enum.EnterpriseCustomerEnum,
			CustomerID:   req.EnterpriseCustomerId,
			EnterpriseID: accountInfo.EnterpriseId,  // 企业
			PersonID:     enterprisePersonEntity.ID, // 人员id
		}); err != nil {
		l.Logger.Error("创建账号失败" + err.Error())
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("创建失败")
	}
	if err = tx.Commit(); err != nil {
		return "", err
	}
	return "操作成功", nil
}
